<?php

namespace backend\components;

use common\constants\Common;
use common\constants\ErrorCode;
use yii\web\Controller;

class BaseController extends Controller
{

    /**
     * @var \yii\web\Request
     */
    protected $request;

    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->request = \Yii::$app->request;
    }


    /**
     * 当前分页
     * @return int
     */
    protected function getPage()
    {
        $page = $this->request->post('page') ?: $this->request->get('page');
        $page = (int)$page;
        if ($page < 1) {
            $page = 1;
        }
        return $page;
    }

    /**
     * 分页条目数
     * @param int $default
     * @param int $max
     * @return int
     */
    protected function getLimit($default = Common::DEFAULT_PAGE_LIMIT, $max = Common::DEFAULT_PAGE_LIMIT_MAX)
    {
        $limit = $this->request->post('limit') ?: $this->request->get('limit');
        $limit = (int)$limit;
        return $limit >= 1 ? ($limit > $max ? $max : $limit) : $default;
    }

    /**
     * 获取多语言
     * @param $errorCode
     * @param $category
     * @return string
     */
    protected function getLangMessage($errorCode, $category = 'error')
    {
        return \Yii::t($category, $errorCode);
    }

    /**
     * API失败返回
     * @param $errorCode
     * @param null $error
     * @param array $response
     */
    protected function _error($errorCode, $error = null, array $response = [])
    {
        $msg = $this->getLangMessage($errorCode);
        if (empty($msg)) {
            $msg = $error;
        }
        return $this->_output($errorCode, $msg, $error, $response);
    }

    /**
     * API成功返回
     * @param array $response
     */
    protected function _success(array $response = [])
    {
        return $this->_output(ErrorCode::SUCCESS, 'success', '', $response);
    }

    /**
     * 输出
     * @param $errorCode
     * @param $msg
     * @param $error
     * @param array $response
     */
    protected function _output($errorCode, $msg, $error, array $response = [])
    {
        $result = [
            'meta' => [
                'code' => (int)$errorCode, //错误码
                'msg' => (string)$msg, //用户端显示的错误信息
                'error' => (string)$error, //开发者查看的错误信息
                'request_uri' => \Yii::$app->request->getPathInfo(), //请求路径
            ],
            'response' => $response ? $response : new \stdClass() //响应信息主体
        ];

        return json_encode($result, JSON_PARTIAL_OUTPUT_ON_ERROR);
    }

}
